<template>
  <div>
    <div class="student-status">
      <template v-if="!route.query.studentId && currentTab !== 'mastery-level'">
        <div class="title">
          <div class="text">学生情况</div>
          <el-segmented
            v-model="studentSituationValue"
            :options="studentSituationOptions"
            block
          />
        </div>
        <div class="tip">鼠标框选目标学生，进行针对性靶向提升！</div>
        <StudentStatusChart
          v-if="count"
          :rateArray
          :knowledgeInfo
          :doubleDimensionData
          :studentSituationValue
          :isLoading
        /><el-empty v-else description="暂无数据" />
      </template>
    </div>
    <div
      class="practice-record"
      :class="{ 'mastery-level-record': currentTab === 'mastery-level' }"
    >
      <div class="title">
        <div class="text">练习记录</div>
        <div class="mark-icon">
          <span class="full-score">满分</span>
          <span class="non-full-score">非满分</span>
        </div>
      </div>
      <PracticeRecordChart
        :practiceRecordArray="practiceRecordArray"
        :isLoading="isLoading"
        :goToTask
      />
      <el-segmented v-model="segmentedValue" :options="segmentedOptions" />
      <template v-if="curTrainRecord.length">
        <template v-for="record in curTrainRecord" :key="record.task_id">
          <el-popover
            placement="left"
            :show-after="500"
            popper-class="custom-popover"
            trigger="hover"
            :content="record.task_name"
          >
            <template #reference>
              <div
                class="data"
                :style="{
                  cursor: record.task_from !== 4 ? 'pointer' : 'default'
                }"
                @click="goToTask(record)"
              >
                <div class="time">
                  <div
                    class="icon"
                    :style="{ backgroundColor: getColorByRate(record.rate) }"
                  >
                    {{ taskMap[record.task_from] }}
                  </div>
                  <div class="text">
                    {{ dayjs(record.train_time).format('M月D日') }}
                  </div>
                </div>
                <div class="count-text">{{ record.count }}道题</div>
                <div class="value">
                  <span
                    class="color-icon"
                    :style="{ backgroundColor: getColorByRate(record.rate) }"
                  ></span>
                  <span>{{ (record.rate * 100).toFixed(2) }}%</span>
                </div>
                <div class="go-btn" v-if="record.task_from !== 4">
                  <el-icon>
                    <IEpRight />
                  </el-icon>
                </div>
              </div>
            </template>
          </el-popover>
        </template>
        <div class="show-more" v-if="showMoreButtonVisible" @click="showMore">
          <span v-if="!isShowMore">展示更多</span>
          <span v-else>隐藏</span>

          <el-icon>
            <IEpArrowUp v-if="isShowMore" />
            <IEpArrowDown v-else />
          </el-icon>
        </div>
      </template>
      <el-empty v-else description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, computed, defineEmits } from 'vue'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs'
import { debounce } from 'lodash'
import StudentStatusChart from './StudentStatusChart.vue'
import PracticeRecordChart from './PracticeRecordChart.vue'
import { getKnowledgeRecord, getKnowledgeStudent } from '@/apis/target-boost'
import { useAuthStore, useKnowledgeStore } from '@/stores'
import { computedStageId } from '@/utils'
import { getColorByRate } from '@/views/target-boost/utils'
import { taskMap } from '../data'
const props = defineProps({
  currentTab: String,
  classId: String,
  currentGradeNum: Number,
  subjectId: Number,
  knowledgeId: Number || String,
  selectTime: Array,
  count: Number,
  knowledgeInfo: Object
})

const route = useRoute()
const authStore = useAuthStore()
const knowledgeStore = useKnowledgeStore()
const emit = defineEmits(['toDetail'])

const studentSituationValue = ref('得分率分布')
const studentSituationOptions = ['得分率分布', '双维度分布']

const rateArray = ref([])
const doubleDimensionData = ref([])
const practiceRecordArray = ref([])
const trainRecord = ref([])
const isLoading = ref(false)

const getRecordAndComputedData = async (isNewSubject = false) => {
  isLoading.value = true
  rateArray.value = []

  const params = {
    school_id: authStore.userInfo.school_id,
    class_id: props.classId || route.query.class_id,
    class_type: +route.query.class_type || authStore.classType,
    grade_num: props.currentGradeNum || +route.query.grade_num,
    subject_id: +route.query.subject_id || authStore.nowGlobalSubjectId,
    stage_id: computedStageId(props.currentGradeNum || +route.query.grade_num),
    start_time: +props.selectTime?.[0] || dayjs('2021-01-01').unix(),
    end_time: +props.selectTime?.[1] || dayjs().unix(),
    ...(route.query?.studentId && { student_id: route.query.studentId })
  }
  if (isNewSubject) {
    params.subject_id = authStore.nowGlobalSubjectId
  }
  if (props.knowledgeId) {
    params.knowledge_id = props.knowledgeId
  }

  try {
    console.log(props.classId, route.query.class_id)
    if (!props.classId && !route.query.class_id) {
      return
    }
    const { data } = await getKnowledgeRecord(JSON.stringify(params))
    console.log(data)
    const practiceRecord = data.train_record || []
    practiceRecordArray.value = practiceRecord.map((item, index) => [
      index,
      +(item.rate * 100).toFixed(2),
      item.train_time,
      item
    ])

    trainRecord.value = practiceRecord
    params.last_frequency = 0
    const studentSituationData = await getKnowledgeStudent(
      JSON.stringify(params)
    )
    knowledgeStore.setStudentSituationData(studentSituationData.data)
    console.log(studentSituationData)

    const res = processStudentSituation(studentSituationData.data || [])
    console.log(rateArray.value)
    rateArray.value = res.rateArray
    doubleDimensionData.value = res.doubleDimensionData
  } catch (error) {
    console.error('获取数据失败', error)
  } finally {
    isLoading.value = false
  }
}

const debouncedGetRecordAndComputedData = debounce(
  async (isNewSubject = false) => {
    await getRecordAndComputedData(isNewSubject)
  },
  500
)

const processStudentSituation = situation => {
  if (!props.knowledgeInfo) return
  const res = new Array(10).fill().map((_, index) => ({
    min: index * 10,
    max: (index + 1) * 10 - 1,
    count: 0,
    field: `${index * 10}-${(index + 1) * 10}%`,
    students: []
  }))
  console.log(situation)
  const averageCount =
    situation.reduce((acc, cur) => acc + cur.count, 0) / situation.length
  console.log(averageCount)
  situation.forEach(item => {
    const rateIndex = Math.min(Math.floor(item.rate * 10), 9)
    res[rateIndex].count++
    res[rateIndex].students.push(item)
    // 计算象限，原点是knowledgeInfo.rate和averageCount
    let { rate } = props.knowledgeInfo
    let { rate: rate1, count: count1 } = item
    rate1 = +(rate1 * 100).toFixed(3)
    count1 = +count1
    // 四象限颜色，原点是红色，右上角是绿色，左下角是黄色，右下角是蓝色
    if (rate1 === rate && count1 === averageCount) {
      item.quadrant = '#ccc' // 灰色 - 原点
    } else if (rate1 > rate && count1 > averageCount) {
      item.quadrant = '#6FA976' // 绿色 - 右上象限
    } else if (rate1 < rate && count1 < averageCount) {
      item.quadrant = '#C44B4F' // 黄色 - 左下象限
    } else if (rate1 > rate && count1 < averageCount) {
      item.quadrant = '#115BB7' // 蓝色 - 右下象限
    } else if (rate1 < rate && count1 > averageCount) {
      item.quadrant = '#FFA500' // 橙色 - 左上象限
    } else if (rate1 === rate && count1 > averageCount) {
      item.quadrant = '#c8d14b' // 浅黄色 - 上轴
    } else if (rate1 > rate && count1 === averageCount) {
      item.quadrant = '#6AD14B' // 浅绿色 - 右轴
    } else if (rate1 === rate && count1 < averageCount) {
      item.quadrant = '#d17c4b' // 橙红色 - 下轴
    } else if (rate1 < rate && count1 === averageCount) {
      item.quadrant = '#FFA500' // 橙色 - 左轴
    } else {
      item.quadrant = '#FFFFFF' // 白色 - 未分类（不应该出现）
    }
  })

  // 双维度数据

  return { rateArray: res, doubleDimensionData: situation }
}

const segmentedValue = ref('全部任务')

const segmentedOptions = ['全部任务', '考试', '练习', '作业', '自习']
const segmentedMap = {
  1: '作业',
  2: '考试',
  3: '练习',
  4: '自习'
}
const isShowMore = ref(false)

const showMore = () => {
  isShowMore.value = !isShowMore.value
}
const showMoreButtonVisible = ref(false)
const curTrainRecord = computed(() => {
  const filteredRecords =
    segmentedValue.value === '全部任务'
      ? trainRecord.value
      : trainRecord.value.filter(
          item => segmentedMap[item.task_from] === segmentedValue.value
        )

  const showMoreRecords = isShowMore.value
    ? filteredRecords
    : filteredRecords.slice(0, 15)
  // eslint-disable-next-line
  showMoreButtonVisible.value = filteredRecords.length > 15
  return showMoreRecords
})

const goToTask = record => {
  console.log(record)
  const { task_from, task_id, task_name } = record
  if (task_from !== 4) {
    emit('toDetail', null, {
      task_id: task_id.split('-')[1],
      origin_task_id: task_id,
      task_name
    })
  }
}

onMounted(async () => {
  await debouncedGetRecordAndComputedData()
})
watch(
  () => [
    props.knowledgeId,
    props.selectTime,
    props.classId,
    authStore.nowGlobalSubjectId,
    props.knowledgeInfo
  ],
  async (v, o) => {
    // authStore.nowGlobalSubjectId新旧对比
    const isNewSubject = v[3] !== o[3]
    console.log('watch')
    await debouncedGetRecordAndComputedData(isNewSubject)
  }
)
</script>
<!-- eslint-disable-next-line -->
<style>
.custom-popover {
  width: auto !important;
}
</style>

<style lang="less" scoped>
.student-status,
.practice-record {
  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 18px;
    padding: 20px 0;
    .mark-icon {
      font-size: 12px;
      color: #a1a1a1;
      .full-score,
      .non-full-score {
        &::before {
          box-sizing: border-box;
          content: '';
          display: inline-block;
          width: 10px;
          height: 10px;
          background-color: #fff;
          border-radius: 50%;
          margin-right: 5px;
        }
      }
      .full-score {
        margin-right: 4px;
        &::before {
          border: 3px solid #f7b446;
        }
      }
      .non-full-score::before {
        border: 3px solid #f75352;
      }
    }
    .text {
      display: flex;
      align-items: center;
      &::before {
        content: '';
        display: inline-block;
        width: 5px;
        height: 18px;
        line-height: 18px;
        background-color: @color-brand-regular;
        margin-right: 5px;
      }
    }
  }
}
.student-status {
  .tip {
    font-size: 14px;
    color: #a1a1a1;
    margin-bottom: 20px;
  }
}

.practice-record {
  min-height: 63vh;

  &.mastery-level-record {
    .title {
      padding-top: 0;

      .text {
        position: relative;
        padding-left: 20px;

        &::before {
          position: absolute;
          content: '';
          background-color: @color-brand-regular;
          width: 7px;
          height: 17px;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
  }

  .title {
    justify-content: space-between;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
  }
  .data {
    position: relative;
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 25px;
    margin-top: 20px;

    .time {
      display: flex;
      height: 25px;
      width: 150px;
      align-items: center;

      .icon {
        width: 20px;
        height: 20px;
        font-size: 13px;
        line-height: 20px;
        margin-right: 5px;
        background-color: #37ecab;
        border-radius: 50%;
        text-align: center;
        color: #fff;
      }
    }

    .count-text {
      font-size: 14px;
      width: 100px;
      font-weight: 500;
    }

    .value {
      display: flex;
      align-items: center;
      width: 100px;

      .color-icon {
        display: inline-block;
        width: 8px;
        height: 8px;
        border-radius: 50%;
        margin-right: 5px;
      }
    }
    .go-btn {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
    }
  }
  .show-more {
    margin-top: 20px;
    text-align: center;
    color: @color-brand-regular;
    cursor: pointer;
  }
}
</style>
